package com.yyq.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import org.joda.time.DateTime;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author yyq
 * @create 2021-10-07 11:56
 * aliyun.oss.file.endpoint=oss-cn-beijing.aliyuncs.com
 * aliyun.oss.file.keyid=LTAI5t9pqbfydw4LTzpLH6k5
 * aliyun.oss.file.keysecret=EfFG2nxZ9oHguLpkDS4SErdAmfDX6f
 * #bucket可以在控制台创建，也可以使用java代码创建
 * aliyun.oss.file.bucketname=music-yyq
 * #music 上传的文件名罢了
 * aliyun.oss.file.filehost=music
 */
public class upFile {
    public static String upload(File file) {
        //获取阿里云存储相关常量
        String endPoint ="oss-cn-beijing.aliyuncs.com";
        String accessKeyId ="LTAI5t9pqbfydw4LTzpLH6k5";
        String accessKeySecret ="EfFG2nxZ9oHguLpkDS4SErdAmfDX6f";
        String bucketName ="music-yyq";
        String fileHost = "music";

        String uploadUrl = null;

        try {
            //判断oss实例是否存在：如果不存在则创建，如果存在则获取
            OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
            if (!ossClient.doesBucketExist(bucketName)) {
                //创建bucket
                ossClient.createBucket(bucketName);
                //设置oss实例的访问权限：公共读
                ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            }

            //获取上传文件流
            InputStream inputStream = new FileInputStream(file);

            //构建日期路径：avatar/2019/02/26/文件名
            String filePath = new DateTime().toString("yyyy/MM/dd");

            //文件名：uuid.扩展名
            String original =file.getName();
            String fileName = UUID.randomUUID().toString();
            String fileType = original.substring(original.lastIndexOf("."));
            String newName = fileName + fileType;
            String fileUrl = fileHost + "/" + filePath + "/" + newName;

            //文件上传至阿里云
            ossClient.putObject(bucketName, fileUrl, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();

            //获取url地址
            uploadUrl = "http://" + bucketName + "." + endPoint + "/" + fileUrl;

        } catch (IOException e) {
            e.printStackTrace();
        }

        return uploadUrl;
    }
}
